package com.yequan.socket.basae;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author : Administrator
 * @date : 2020/2/14
 */
public class Server {

    private final static int port = 1122;

    private ServerSocket serverSocket;

    public Server() {
        try {
            serverSocket = new ServerSocket(port, 3);
            System.out.println("服务器启动!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void service() {
        while (true) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
                System.out.println("新的连接已经建立: " + socket.getInetAddress() + " : " + socket.getPort());
                acceptMessage(socket);
                sendMessage(socket);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != socket) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void sendMessage(Socket socket) throws IOException {
        OutputStream outputStream = socket.getOutputStream();
        PrintWriter printWriter = new PrintWriter(outputStream);
        printWriter.write("我是总部,我已收到你们的信息,注意安全");
        printWriter.flush();
        socket.shutdownOutput();
        printWriter.close();
        outputStream.close();
    }

    private void acceptMessage(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line = null;
        StringBuffer stringBuffer = new StringBuffer();
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        System.out.println("总部收到特工信息: " + stringBuffer.toString());
        bufferedReader.close();
        inputStreamReader.close();
        inputStream.close();
        socket.shutdownOutput();
    }

    public static void main(String[] args) throws InterruptedException {
        Server server = new Server();
//        Thread.sleep(60000 * 10);
        server.service();
    }

}
